package com.qys.livesMall.shop.controller.sys;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.common.message.MessageServer;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.common.utils.MessageUtils;
import com.qys.livesMall.shop.constants.OrderStatus;
import com.qys.livesMall.shop.enums.ShopMessageEnum;
import com.qys.livesMall.shop.mapper.ShopOrderInfoMapper;
import com.qys.livesMall.shop.modal.dto.OrderSkuDto;
import com.qys.livesMall.shop.modal.dto.ShopOrderExpressDto;
import com.qys.livesMall.shop.modal.dto.ShopSalesDto;
import com.qys.livesMall.shop.modal.entity.ShopOrder;
import com.qys.livesMall.shop.modal.entity.ShopOrderIdea;
import com.qys.livesMall.shop.modal.entity.ShopOrderInfo;
import com.qys.livesMall.shop.modal.entity.ShopOrderSku;
import com.qys.livesMall.shop.modal.query.QueryOrder;
import com.qys.livesMall.shop.modal.query.QueryShopSalesDto;
import com.qys.livesMall.shop.service.ShopOrderIdeaService;
import com.qys.livesMall.shop.service.ShopOrderInfoService;
import com.qys.livesMall.shop.service.ShopOrderSkuService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gmx
 * @since 2023-06-19
 */
@RestController
@RequestMapping("/sys/shopOrderInfo")
@Tag(name="sys-用户订单管理",description="sys-用户订单管理")
public class SysShopOrderInfoController {
    @Resource
    private ShopOrderInfoService orderInfoService;
    @Resource
    private ShopOrderInfoMapper orderInfoMapper;
    @Resource
    private ShopOrderSkuService orderSkuService;
    @Resource
    private ShopOrderIdeaService ideaService;

    @Autowired
    private MessageServer messageServer;



    @GetMapping("/statistics")
    public R<Map<String,Object>> statistics(){
        QueryWrapper<ShopOrderInfo> goodsInfoQueryWrapper = new QueryWrapper<>();
        long total = orderInfoService.count();
        List<Object> reslut = orderInfoMapper.selectObjs(goodsInfoQueryWrapper.select("SUM(moneys)"));
        BigDecimal sum =(BigDecimal) reslut.get(0);
        QueryWrapper<ShopOrderInfo> goodsInfoQueryWrapperNew = new QueryWrapper<>();
        goodsInfoQueryWrapperNew.apply("FROM_UNIXTIME(create_time/1000,'%Y-%m-%d') = CURDATE()");
        long todayTotal = orderInfoService.count(goodsInfoQueryWrapperNew);
        List<Object> todayreslut=orderInfoMapper.selectObjs(goodsInfoQueryWrapperNew.select("SUM(moneys)"));
        BigDecimal todaysum =(BigDecimal) todayreslut.get(0);
        if(ObjectUtils.isEmpty(todaysum)){
            todaysum=BigDecimal.ZERO;
        }
        Map<String,Object> map = new HashMap<>();
        map.put("total",total);
        map.put("sumMoney",sum);
        map.put("todayTotal",todayTotal);
        map.put("todaySumMoney",todaysum);
        return R.ok(map);
    }

    @PostMapping("/express")
    public R edit(@RequestBody ShopOrderExpressDto expressDto){
        long now = System.currentTimeMillis();
        ShopOrderSku orderSku = orderSkuService.getById(expressDto.getSkuId());
        if (!Objects.equals(orderSku.getOrderStatus(),OrderStatus.SHIPPED)){
            return messageServer.failMsg(ShopMessageEnum.SHOP_ORDER_STATUS_EXCEPTION);
        }
        if (ObjectUtils.isEmpty(orderSku))return R.fail(MessageUtils.message("system.error.order"));
        orderSku.setConsignTime(now);
        orderSku.setExpress(expressDto.getExpressNum());
        try {
            if(!orderSkuService.updateById(orderSku)) throw new QysException(MessageUtils.message("system.error.order"));
        }catch (QysException e){
            R.fail(e.getMessage());
        }
        return R.ok();
    }
    @Operation(summary = "查询订单取消原因")
    @GetMapping("/delIdea/{orderId}")
    public R<ShopOrderIdea> delIdea(@PathVariable Long orderId){
        LambdaQueryWrapper<ShopOrderIdea> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopOrderIdea::getOrderId,orderId);
        ShopOrderIdea idea = ideaService.getOne(queryWrapper);
        return ObjectUtils.isNotEmpty(idea)?R.ok(idea):R.fail(MessageUtils.message("no.reason"));
    }

    @GetMapping("/{orderId}")
    public R<ShopOrder> get(@PathVariable Long orderId){
        ShopOrderInfo orderInfo = orderInfoService.getById(orderId);
        if (orderInfo.getIsDelete().equals("1")){
            return R.fail(MessageUtils.message("shop.not.find.order"));
        }
        if (ObjectUtils.isEmpty(orderInfo))return R.fail(MessageUtils.message("system.error.order"));
        LambdaQueryWrapper<ShopOrderSku> orderSkuLambdaQueryWrapper= new LambdaQueryWrapper<>();
        orderSkuLambdaQueryWrapper.eq(ShopOrderSku::getOrderId,orderId);
        List<ShopOrderSku> orderSkus = orderSkuService.list(orderSkuLambdaQueryWrapper);
        if (orderSkus.size()==0)return R.fail(MessageUtils.message("system.error.order"));
        ShopOrder shopOrder = new ShopOrder();
        shopOrder.setOrderInfo(orderInfo);
        shopOrder.setOrderSkus(orderSkus);

        return R.ok(shopOrder);
    }
    @Operation(summary = "结束订单")
    @PostMapping("/handle/{skuId}")
    public R handle(@PathVariable Long skuId){
        long now = System.currentTimeMillis();
        ShopOrderSku orderSku = orderSkuService.getById(skuId);
        switch (orderSku.getOrderStatus()){
            case 0:
                ShopOrderIdea orderIdea = new ShopOrderIdea();
                orderIdea.setIdea(MessageUtils.message("system.cancel"));
                orderIdea.setDescription(MessageUtils.message("system.cancel"));
                orderIdea.setCreateTime(now);
                orderIdea.setOrderId(orderSku.getOrderId());
                return orderInfoService.cancel(orderIdea);
            case 1:
                return orderInfoService.operation(orderSku.getId());
            case 2:
                return R.fail(MessageUtils.message("order.completed"));
        }
        return R.ok();
    }

    @PostMapping("/list")
    @Operation(summary = "订单列表")
    public R<Page<OrderSkuDto>> list(@RequestBody QueryOrder queryOrder){
        Page<OrderSkuDto> page = Page.of(queryOrder.getCurrent(),queryOrder.getSize());
        Page<OrderSkuDto> list = orderInfoMapper.queryOrderSku(page,queryOrder);
//        List<Long> shopIds = list.getRecords().stream().map(OrderSkuDto::getShopId).collect(Collectors.toList());
//        List<H2ShopBase> shopList = baseDao.listByIds(shopIds);
//        List<OrderSkuDto> orderSkuDtoList = list.getRecords().stream().map(orderSkuDto -> {
//            H2ShopBase thisList = shopList.stream().filter(h2ShopBase -> h2ShopBase.getId().equals(orderSkuDto.getShopId())).findFirst().orElse(null);
//            if (thisList != null) {
//                orderSkuDto.setShopName(thisList.getShopName());
//            }
//            return orderSkuDto;
//        }).collect(Collectors.toList());
//        list.setRecords(orderSkuDtoList);
        return R.ok(list);
    }

    @PostMapping("/salesPage")
    @Operation(summary = "已售商品")
    public R<Page<ShopSalesDto>> shopSalesPage(@RequestBody QueryShopSalesDto data){
        Page<ShopSalesDto> page = Page.of(data.getCurrent(), data.getSize());
        Page<ShopSalesDto> list = orderInfoMapper.queryOrderShop(page, data);
        return R.ok(list);
    }


}
